package com.task.mall.controller.admin;

import com.google.gson.Gson;
import com.task.mall.bean.Result;
import com.task.mall.bean.User;
import com.task.mall.service.UserService;
import com.task.mall.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    Gson gson = new Gson();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/", "");
        if ("allUser".equals(action)){
            allUser(request,response);
        }if ("deleteUser".equals(action)){
            deleteUser(request,response);
        }if ("searchUser".equals(action)){
            searchUser(request,response);
        }
    }

    /**
     * 输入关键字搜索用户
     * @param request
     * @param response
     */
    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        List<User> userList = userService.searchUser(word);
        Result res = new Result();
        //获取到指定word的用户信息显示到界面
        res.setCode(0);
        res.setData(userList);
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 删除用户
     * @param request
     * @param response
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int result = userService.deleteUser(id);
        Result res = new Result();
        if (result == 200){
            res.setCode(0);
        }else{
            res.setCode(10000);
            res.setMessage("删除用户异常，请稍后重试");
        }
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 查询具体的user用戶信息
     * @param request
     * @param response
     */
    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> userList = userService.queryAllUser();
        Result res = new Result();
        res.setCode(0);
        res.setData(userList);
        response.getWriter().println(gson.toJson(res));
    }
}
